package com.openspring.platform.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.swing.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.openspring.framework.service.AbstractGenericService;
import com.openspring.platform.dao.DeptDAO;
import com.openspring.platform.model.Dept;
import com.openspring.platform.model.node.DeptNode;
import com.openspring.platform.service.DeptService;

@Service("deptService")
public class DeptServiceImpl extends AbstractGenericService<Dept, Long> implements DeptService {

	private DeptDAO deptDAO;
	
	@Resource(name = "deptDAO")
	public void setDeptDAO(DeptDAO deptDAO) {
		this.deptDAO = deptDAO;
		super.setGenericDAO(deptDAO);
	}

	@Override
	public List<Dept> findAllChildren(Long id) {
		return deptDAO.queryAllChildren(id);
	}

	@Override
	public List<Dept> findChildren(Long id) {
		return deptDAO.queryChildren(id);
	}

	@Override
	public DeptNode getStaticTree() {
		DeptNode root = new DeptNode();
		root.setText(".");
		List<Dept> entities = deptDAO.queryAll();
		Map<Long, DeptNode> map = new HashMap<Long, DeptNode>();
		Iterator<Dept> iter = entities.iterator();
		while(iter.hasNext()) {
			DeptNode node = new DeptNode();
			Dept entity = iter.next();
			BeanUtils.copyProperties(entity, node);
			node.setText(entity.getCnName());
			map.put(node.getId(), node);
		}
		Set<Map.Entry<Long, DeptNode>> entrySet = map.entrySet();
		Iterator<Map.Entry<Long, DeptNode>> iter1 = entrySet.iterator();
		while(iter1.hasNext()) {
			DeptNode node = iter1.next().getValue();
			if(node.getParentId() == 0) {
				root.getChildren().add(node);
			} else {
				map.get(node.getParentId()).getChildren().add(node);
			}
		}
		root.sort(SortOrder.ASCENDING);
		return root;
	}
}
